//
//  CalendarTopFilterView.swift
//  EYEE
//
//  Created by 虫虫乐 on 2018/12/28.
//  Copyright © 2018年 zali. All rights reserved.
//  首页-日历顶部筛选view

import UIKit

struct CTopFilterModel {
    var title: String = ""
    var state: String = "0"
    init(title: String, state: String = "0") {
        self.title = title
        self.state = state
    }
}

protocol CalendarTopFilterViewDelegate: NSObjectProtocol {
    //MARK: - 声明代理
    /// segment各item点击回调
    ///
    /// - Parameters:
    ///   - data: 点击的数据
    ///   - indexPath: 点击的indexPath
    func cTopFilterSelectedData(_ data:CTopFilterModel, indexPath:IndexPath)
}

extension CalendarTopFilterViewDelegate {
    func cTopFilterSelectedData(_ data:CTopFilterModel, indexPath:IndexPath) {
    }
}

class CalendarTopFilterView: UIView {
    //MARK: - 声明属性
    //状态条
    lazy var stateCollectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: itemW, height: itemH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let collectionView = UICollectionView(frame: .zero,
                                              collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate   = self
        collectionView.register(CTopFilterCollectionCell.self, forCellWithReuseIdentifier: CTopFilterCollectionCell.reuseId())
        return collectionView
    }()
    
    //更多按钮
    lazy var moreBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "calendar_ic_more"), for: .normal)
        return btn
    }()
    
    //全部状态弹层
    lazy var allFilterView: CalendarAllFilterAlertView = {
        let view = CalendarAllFilterAlertView(frame: .zero)
        view.delegate = self
        return view
    }()
    
    //分割线
    lazy var line: UIView = {
        let line = UIView()
        line.backgroundColor = UIColor.init(hexString: "F2F2F2")
        return line
    }()
    
    weak var delegate : CalendarTopFilterViewDelegate?
    var selectedIndex: Int  = 0
    var dataList:[CTopFilterModel]   = []
    let itemW:CGFloat = screenWidth/7.0
    let itemH:CGFloat = 44.up
    
    //MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 搭建UI
    func setupUI() {
        backgroundColor = UIColor.white
        
        //添加
        addSubview(stateCollectionView)
        addSubview(moreBtn)
        addSubview(line)
        
        //布局
        stateCollectionView.snp.makeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(-itemW)
        }
        moreBtn.snp.makeConstraints { (make) in
            make.right.top.bottom.equalToSuperview()
            make.left.equalTo(stateCollectionView.snp.right)
        }
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5.up)
        }
        
        //添加事件
//        moreBtn.addTarget { [weak self] (control) in
//            guard let weakSelf = self else {return}
//            weakSelf.showAllFilterView()
//        }
    }
}

extension CalendarTopFilterView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    //MARK: - 事件
    //刷新数据
    func refreshDatas(_ list:[CTopFilterModel],selectedIndex:Int = 0) {
        self.dataList = list
        self.selectedIndex = selectedIndex
        self.stateCollectionView.reloadData()
    }
    
    //刷新滚动位置
    func refreshScrollToIndexPath(_ indexPath:IndexPath) {
        self.selectedIndex = indexPath.row
        self.stateCollectionView.reloadData()
        self.stateCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }
    
    //MARK: - 代理
    //MARK: UICollectionViewDelegate
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CTopFilterCollectionCell.reuseId(), for: indexPath) as! CTopFilterCollectionCell
        if indexPath.row < self.dataList.count {
            let model = self.dataList[indexPath.row]
            cell.cellRefreshDatas(model, isSelected: self.selectedIndex == indexPath.row)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = self.dataList[indexPath.row]
        let size:CGSize = model.title.boundingRect(with: CGSize(width: 1000 , height: itemH), font: UIFont.pingfangSemibold(size: 14.up)!)
//        let width = size.width < itemW  ? itemW : (size.width + 10)
        let width = size.width + 24//24为左右边距
        return CGSize(width: width, height: itemH)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if  self.selectedIndex == indexPath.row {
            return
        }
        if indexPath.row < self.dataList.count {
            self.refreshScrollToIndexPath(indexPath)
            guard let cDelegate = self.delegate else {
                return
            }
            let model = self.dataList[indexPath.row]
            cDelegate.cTopFilterSelectedData(model,indexPath: indexPath)
        }
    }
}

extension CalendarTopFilterView: CalendarAllFilterAlertViewDelegate {
    //MARK: - 弹层相关事件
    //显示弹层
    func showAllFilterView() {
        if self.dataList.count <= 0 {return}
        allFilterView.show()
        allFilterView.refreshDatas(self.dataList, selectedIndex: self.selectedIndex)
    }
    
    //MARK: - 弹层代理
    //点击弹层各状态代理回调
    func cAllFilterSelectedData(_ data: CTopFilterModel, indexPath: IndexPath) {
        self.refreshScrollToIndexPath(indexPath)
        guard let cDelegate = self.delegate else {
            return
        }
        cDelegate.cTopFilterSelectedData(data,indexPath: indexPath)
    }
}

class CTopFilterCollectionCell: UICollectionViewCell {
    //MARK: - 声明属性
    lazy var titleBtn : UIButton = {
        let titleBtn = UIButton(type: .custom)
        titleBtn.isUserInteractionEnabled = false
        titleBtn.titleLabel?.numberOfLines = 1
        titleBtn.titleLabel?.textAlignment = .center
        titleBtn.titleLabel?.font = UIFont.pingfangMedium(size: 14.up)
        titleBtn.setTitleColor(UIColor.gray, for: .normal)
        titleBtn.setTitleColor(UIColor.black, for: .selected)
        titleBtn.isUserInteractionEnabled = false
        titleBtn.backgroundColor = UIColor.white
        return titleBtn
    }()

    //MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    static func reuseId() -> String {
        return NSStringFromClass(CTopFilterCollectionCell.self)
    }
    
    //MARK: - 搭建UI
    func setupUI() {
        contentView.addSubview(titleBtn)
        titleBtn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: - 刷新数据
    func cellRefreshDatas(_ data:CTopFilterModel, isSelected: Bool) {
        self.titleBtn.setTitle(data.title, for: .normal)
        self.titleBtn.isSelected = isSelected
    }
}


